package main

import (
	//"fmt"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/ngaut/log"
)

var (
	mode = flag.Int("m", 1, "mode")
)

func tUseHttpClient()  {
	c := &http.Client{
		Timeout: time.Duration(2*time.Second),
	}

	req := &http.Request{}
	body := "{\"hello\": \"world\"}"
	///////////////// 尽管是get请求，但貌似给了body也没关系 ??
	br := strings.NewReader(body)
	//req.ContentLength = int64(len(body))
	req.Body = ioutil.NopCloser(br)

	urL, _ := url.Parse("http://9.134.5.74:8083")
	req.URL = urL

	for i:=0; i<5; i++ {
		resp, err := c.Do(req)
		if err != nil {
			log.Debugf("err: %v", err)
		} else {
			defer resp.Body.Close()
			io.Copy(os.Stdout, resp.Body)
		}
	}
}

func tSendPost() {
	for i:=0; i<=1; i++ {
		v := url.Values{}
		v.Set("cs", "hello world " + strconv.Itoa(i))
		body := ioutil.NopCloser(strings.NewReader(v.Encode())) //把form数据编下码
		client := &http.Client{}
		req, _ := http.NewRequest("POST", "http://localhost:24756/hello", body)

		//这个一定要加，不加form的值post不过去，被坑了两小时 （https://my.oschina.net/tongjh/blog/348091）
		// 貌似可以不加 ??
		//req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value") 
		log.Debugf("req: %v", req)                                                         

		resp, err := client.Do(req) //发送
		resp.Body.Close()     //一定要关闭resp.Body
		data, _ := ioutil.ReadAll(resp.Body)
		log.Infof("data: %v, err:%v", string(data), err)
	}
}

func tSendPost2() {
	//req, err := http.NewRequest("POST","http://localhost:24756/hello", strings.NewReader("abc"))
}

func main()  {
	flag.Parse()

	switch (*mode) {
	case 0:
		tClientWithShortConnPerRequest()  // short conn per request
	case 1:
		tHttpShortConn()
	case 2:
		tHttpLongConn()
	case 3:
		tUseHttpClient()
	case 4:
		tSendPost()
	case 5:
		tUseHttpClient()
	default:
		fmt.Println("no such mode")
	}
}